package com.weacar.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weacar.R;
import com.weacar.activity.CarDetailActivity;
import com.weacar.activity.LoginActivity;
import com.weacar.activity.MainActivity;
import com.weacar.activity.MessageCenterActivity;
import com.weacar.activity.SearchIndexActivity;
import com.weacar.activity.SearchResultActivity;
import com.weacar.adapter.HomeKeyGvAdapter;
import com.weacar.adapter.TestAdapter;
import com.weacar.adapter.TimeCountDownAdapter;
import com.weacar.bean.BannerBean;
import com.weacar.bean.BaseBean;
import com.weacar.bean.CarBean;
import com.weacar.bean.HomeKeyBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.view.FitScrollViewGridView;
import com.weacar.view.FitScrollViewListView;
import com.weacar.view.GlideImageLoader;
import com.youth.banner.Banner;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeFragment extends Fragment {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.gv_key_value_home)
    FitScrollViewGridView gv_key_value_home;
    @BindView(R.id.lv_recommend)
    FitScrollViewListView lv_recommend;
    @BindView(R.id.refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_red_point)
    ImageView iv_red_point;

    private Unbinder unbinder;
    private MainActivity mainActivity;

    private List<CarBean.MsgBean> al;
    private TimeCountDownAdapter timeCountDownAdapter;

    private int page = 1;
    private int refresh_flag = 0;

    // 出价返回码
    private int myRequestCode = 1;


    @OnClick({R.id.cl_head, R.id.iv_message})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.cl_head:
                startActivity(new Intent(getActivity(), SearchIndexActivity.class));
                break;
            case R.id.iv_message:
                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                break;
        }
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, null);
        unbinder = ButterKnife.bind(this, v);
        mainActivity = (MainActivity) getActivity();
        al = new ArrayList<>();
        initBanner();
        initData();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                al.clear();
                refresh_flag = 1;
                page = 1;
                getRecommend();

            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refresh_flag = 2;
                page = page + 1;
                getRecommend();
            }
        });

        return v;
    }


    // 初始化广告图
    public void initBanner() {
        getBanner();
    }

    /**
     * 获取轮播图
     */
    public void getBanner() {
        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getActivity(), "当前网络不可用");
            return;
        }

        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_banner_url);
        params.setCacheMaxAge(0);
        mainActivity.showLoading("数据加载中...");
        LogUtils.d("banner_url = " + params.getUri());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("result = " + result);
                mainActivity.closeLoading();
                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean != null && baseBean.getCode() == 1) {
                    try {
                        BannerBean loginBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), BannerBean.class);
                        // 加载轮播图
                        if (loginBean != null && loginBean.getMsg() != null && loginBean.getMsg().size() > 0) {
                            List<String> images = new ArrayList<>();
                            for (int i = 0; i < loginBean.getMsg().size(); i++) {
                                images.add(loginBean.getMsg().get(i).getUrl());
                            }
                            banner.setImageLoader(new GlideImageLoader());
                            banner.setImages(images);
                            banner.setDelayTime(3000);
                            banner.start();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeLoading();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mainActivity.closeLoading();
            }

            @Override
            public void onFinished() {
                mainActivity.closeLoading();
            }
        });


    }

    // 初始化关键词
    public void initData() {
        iv_red_point.setVisibility(View.GONE);
        getKey();
        getRecommend();
    }


    // 获取首页为您推荐
    public void getRecommend() {

        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getActivity(), "当前网络不可用");
            return;
        }
        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_recommend_car);
        params.setCacheMaxAge(0);
        JSONObject js_request = new JSONObject();
        try {
            js_request.put("page", String.valueOf(page));
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.d("recommend_url = " + params.getUri());
        // LogUtils.d("params = " + params.getBodyContent());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("recommend_result = " + result);
                if (refresh_flag == 1) {
                    refreshLayout.finishRefresh();
                } else if (refresh_flag == 2) {
                    refreshLayout.finishLoadmore();
                }

                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean != null && baseBean.getCode() == 1) {
                    try {
                        CarBean carBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), CarBean.class);
                        if (carBean != null && carBean.getMsg() != null) {
                            if (refresh_flag == 2 && carBean.getMsg().size() == 0) {
                                ToastUtil.showShort(getContext(), "没有更多数据了.");
                            }
                            al.addAll(carBean.getMsg());
                            timeCountDownAdapter = new TimeCountDownAdapter(al, getContext());
                            lv_recommend.setAdapter(timeCountDownAdapter);
                            lv_recommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    if (mainActivity.loginBean != null) {
                                        Intent intent = new Intent(mainActivity, CarDetailActivity.class);
                                        intent.putExtra("web_url", al.get(i).getWeb_url());
                                        LogUtils.d("web_url = " + al.get(i).getWeb_url());
                                        intent.putExtra("car_id", al.get(i).getId());
                                        intent.putExtra("token", mainActivity.loginBean.getMsg().getToken());
                                        intent.putExtra("auction_type", al.get(i).getAuction_type());
                                        intent.putExtra("online_price", al.get(i).getOnline_price());
                                        // 一口价
                                        if (al.get(i).getAuction_type() == 2) {
                                            startActivityForResult(intent, myRequestCode);
                                        } else {
                                            startActivity(intent);
                                        }
                                    } else {
                                        startActivity(new Intent(getActivity(), LoginActivity.class));
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == myRequestCode && resultCode == 3) {
            mainActivity.showMyPriceFragment();
        }
    }

    // 获取首页关键词
    public void getKey() {
        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getActivity(), "当前网络不可用");
            return;
        }

        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_home_car_key);
        params.setCacheMaxAge(0);
        LogUtils.d("key_url = " + params.getUri());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("key_result = " + result);
                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean != null && baseBean.getCode() == 1) {
                    try {
                        final HomeKeyBean homeKeyBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), HomeKeyBean.class);
                        gv_key_value_home.setAdapter(new HomeKeyGvAdapter(getContext(), R.layout.item_gv_key_home, homeKeyBean.getMsg()));
                        gv_key_value_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                                intent.putExtra("key", homeKeyBean.getMsg().get(i).getName());
                                startActivity(intent);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timeCountDownAdapter != null) {
            timeCountDownAdapter.cancelAllTimers();
        }
        if (unbinder != null) {
            unbinder.unbind();
        }

    }
}
